import 'package:flutter/material.dart';

/// 文本输入改变监听
/// 1. TextField -- 使用onChanged回调和TextEditingController
/// 2. TextFormField
///   - 创建TextEditingController
///   - 为TextFormField应用TextEditingController
///   - 创建打印最后一个值的函数
///   - 监听控制器文本的改变

class TextChangeApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Text Change Demo',
      theme: ThemeData(primarySwatch: Colors.red),
      home: TextChangeAppPage(),
    );
  }
}

class TextChangeAppPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => TextChangeAppPageState();
}

class TextChangeAppPageState extends State<TextChangeAppPage> {
  // 创建输入框文本编辑控制器
  final TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    // 添加监听
    _controller.addListener(_printLatestValue);
  }

  // 打印最后一次的值
  _printLatestValue() {
    // 打印文本内容
    print('Second text field: ${_controller.text}');
  }

  @override
  void dispose() {
    // 销毁
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Retrieve Text Input'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            children: <Widget>[
              TextField(
                onChanged: (text) {
                  print('First text field: $text');
                },
              ),
              // TextFormField中，无法使用onChanged方法
              TextFormField(
                controller: _controller,
              )
            ],
          ),
        ));
  }
}
